const md5 = require('js-md5');
var APP_ID = require('../config').APP_ID;

var SECRET_KEY = require('../config').SECRET_KEY;
var url = require('../config').url;
var toLanguage = require('../config').toLanguage;

async function main(text) {
    // 生成时间戳作为salt  
    const salt = String(Date.now());
    // 构建要签名的字符串  
    const stringToSign = `${APP_ID}${text}${salt}${SECRET_KEY}`;
    // 使用CryptoJS进行MD5加密  
    const sign = md5(stringToSign);

    // 构建请求参数  
    const params = new URLSearchParams({
        q: text,
        from: 'zh',
        to: toLanguage,
        appid: APP_ID,
        salt: salt,
        sign: sign
    });
    var result = null;
    const response = await fetch(url + '?' + params.toString(), {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: params
    })
    result = await response.json();
    if (result.trans_result && result.trans_result.length != 0) {
        console.log("翻译内容：" + text);
        console.log("翻译结果："+ result.trans_result[0].dst.trim())
        console.log("-------------------------------------------------------------------")
        return result.trans_result[0].dst
    } else {
        console.log("****************************************************************")
        console.log(result)
        console.log("****************************************************************")
        return null
    }
}
main("你好，百度翻译")